package com.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类，用于发送HTTP GET和POST请求。
 */
public class HttpClientUtils {

    // 设置请求超时时间为5秒
    static final int TIMEOUT_MSEC = 5 * 1000;

    /**
     * 发送GET方式请求
     * @param url 请求地址
     * @param paramMap 请求参数键值对
     * @return 响应内容
     */
    public static String doGets(String url, Map<String, String> paramMap) {
        // 创建Httpclient对象
        //CloseableHttpClient httpClient = HttpClients.createDefault();
        SSLContext sslContext = SSLContexts.createDefault();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)  // 如果你不需要验证主机名，可以使用 NoopHostnameVerifier
                .build();

        String result = "";
        CloseableHttpResponse response = null;

        try {
            // 构建请求URI
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }
            URI uri = builder.build();

            // 创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 发送请求
            response = httpClient.execute(httpGet);

            // 判断响应状态，如果状态码为200，表示请求成功
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            // 捕获并打印异常
            e.printStackTrace();
        } finally {
            try {
                // 关闭响应和客户端
                response.close();
                httpClient.close();
            } catch (IOException e) {
                // 捕获并打印关闭资源时的异常
                e.printStackTrace();
            }
        }

        return result;
    }


    /**
     * 发送GET方式请求
     * @param url 请求地址
     * @param paramMap 请求参数键值对
     * @return 响应内容
     */
    public static String doGet(String url, Map<String, String> paramMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = "";
        CloseableHttpResponse response = null;

        try {
            // 构建请求URI
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }
            URI uri = builder.build();

            // 创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 发送请求
            response = httpClient.execute(httpGet);

            // 判断响应状态，如果状态码为200，表示请求成功
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            // 捕获并打印异常
            e.printStackTrace();
        } finally {
            try {
                // 关闭响应和客户端
                response.close();
                httpClient.close();
            } catch (IOException e) {
                // 捕获并打印关闭资源时的异常
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 发送POST方式请求
     * @param url 请求地址
     * @param paramMap 请求参数键值对
     * @return 响应内容
     * @throws IOException 网络异常
     */
    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            // 设置请求配置
            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            // 获取响应内容
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            // 抛出异常
            throw e;
        } finally {
            try {
                // 关闭响应
                response.close();
            } catch (IOException e) {
                // 捕获并打印关闭资源时的异常
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * 发送POST方式请求，适用于JSON格式数据
     * @param url 请求地址
     * @param paramMap 请求参数键值对
     * @return 响应内容
     * @throws IOException 网络异常
     */
    public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            if (paramMap != null) {
                // 构造json格式数据
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(), param.getValue());
                }
                StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
                // 设置请求编码
                entity.setContentEncoding("utf-8");
                // 设置数据类型
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            // 设置请求配置
            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            // 获取响应内容
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            // 抛出异常
            throw e;
        } finally {
            try {
                // 关闭响应
                response.close();
            } catch (IOException e) {
                // 捕获并打印关闭资源时的异常
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * 构建请求配置
     * @return RequestConfig对象
     */
    private static RequestConfig builderRequestConfig() {
        // 设置连接超时、请求超时和套接字超时时间
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC)
                .build();
    }

}